<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addUserForm">添加角色</el-button>
        </el-col>
      </el-row>

      <!-- 添加角色表单 -->
      <!-- 添加用户的对话话框 -->
    <el-dialog title="添加用户" @close="addUserDialogClosed" :visible.sync="addUserDialogVisible" width="50%">
      <!-- 内容主题 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="角色" prop="userName">
          <el-input v-model="addForm.userName"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="passWord">
          <el-input v-model="addForm.passWord"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
      <!-- 角色列表区b域 -->
      <el-table
        :data="roleList"
        stripe
        border
      >
        <!-- type expand是展开列 -->
        <el-table-column type="expand">
          <template v-slot="scope">
            <!-- 栅格系统 -->
            <el-row
              :class="['bdbottom',i1 === 0 ? 'bdtop' :'' , 'vcenter'] "
              v-for="(item1 , i1) in scope.row.children"
              :key="i1"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag>{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级和三级权限 -->
              <el-col :span="19">
                <!-- 通过for循环嵌套渲染二级权限 -->
                <el-row
                  :class="[i2 === 0 ? '' :'bdtop', 'vcenter']"
                  v-for="(item2,i2) in item1.children"
                  :key="i2"
                >
                  <el-col :span="6">
                    <el-tag type="success">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="(item3, i3) in item2.children"
                      :key="i3"
                      closable
                      @close="removeRightByIndex(scope.row,item3.id,i1,i2,i3)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- type index 是索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template v-slot="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini">删除</el-button>
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showSetRightDialog(scope.row.id)"
            >查询权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限功能 Dialog-->
    <!-- 可用node 建立数据库 进行权限分配操作 -->
    <el-dialog title="查询权限" :visible.sync="setRightDialogVisible"  @close="setRightDialogClose" width="50%">
      <!-- 树形控件 -->
      <el-tree :data="rightList" :props="treeProps"  node-key="id" default-expand-all :default-checked-keys="defaultKeys"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRightDialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>
export default {
  data() {
    // 验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      //邮箱正则
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }
    // 验证手机号规则
    var checkMobile = (rule, value, cb) => {
      //手机号正则
      const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) return cb()
      cb(new Error('请输入合法的手机号'))
    }
    return {
      roleList: [],
      //   所有权限的数据
      rightList: [],
      //控制点击分配权限对话框的显示与隐藏
      setRightDialogVisible: false,

      // 控制添加角色表单对话框显示与隐藏
      addUserDialogVisible: false,
      treeProps: {
        children: 'children',
        label: 'authName',
      },
      // 默认选中的节点
      defaultKeys:[],

      // 添加用户验证
      addForm: {
        userName: '',
        passWord: '',
        email: '',
        mobile: '',
      },

      // 添加用户验证对象
      addFormRules: {
        userName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur',
          },
        ],
        passWord: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 15 个字符',
            trigger: 'blur',
          },
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入电话号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' },
        ],
      }
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const { data: res } = await this.$http.get('/role')
      if (res.meta.status !== 200) {
        return this.$message.error('请求失败')
      }
      this.roleList = res.data
    },
    // 删除事件
    async removeRightByIndex(role, rightId, ...rest) {
      // 弹框提示 element-ui message-Box
      const confirmResult = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      //   .catch 是用户点击取消时捕获到操作

      if (confirmResult !== 'confirm') {
        // 如果不等于表示用户 取消了删除
        return this.$message.info('取消了删除')
      }
      // 如果confirmResult 等于 'confirm' 表示用户点击了确认

      // console.log('确认了删除');
      // 此时应该发起删除的请求
      const { data: res } = await this.$http.delete('role/delete', {
        roleID: role.id,
        rightID: rightId,
      })
      if (res.meta.status !== 200) {
        return this.$message.error('请求失败')
      }
      let [index1, index2, index3] = rest
      console.log(this.roleList, rest, index1, index2, index3, role)

      // 请求成功利用index 删除数组
      var i = this.roleList.findIndex((item) => item.id === role.id)
      this.roleList[i].children[index1].children[index2].children.splice(
        index3,
        1
      )
    },
    // 分配权限
    async showSetRightDialog(id) {
      this.setRightDialogVisible = true
      // 所有权限的数据
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限失败')
      }
      this.rightList = res.data
      this.defaultKeys.push(id);
    },
    // 关闭权限分配对话框事件
    setRightDialogClose(){
      this.defaultKeys = [];
    },

    // 关闭添加角色dialog
    addUserDialogClosed() {
      this.addUserDialogVisible = false; 
    },

    // 点击添加角色按钮事件
    addUserForm() {
      this.addUserDialogVisible = true;
    },

    // addForm表单确定按钮
    addUser() {
      this.$refs.addFormRef.validate((valid) => {
        if(!valid) return;
        // 如果校验成功则发起添加用户请求

      })
    }
  },
}
</script>
<style lang="less" scoped>
.el-table {
  margin-top: 15px;
}
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>